<template>
  <div>
    <el-table
      ref="table"
      v-loading="listLoading"
      border
      :data="listData"
      :empty-text="emptyText"
      element-loading-text="Loading"
      :row-key="rowKey"
      @selection-change="handleSelectionChange"
    >
      <el-table-column v-if="multiSelect" type="selection" width="45" />
      <el-table-column type="expand" width="35">
        <template slot-scope="scope">
          <el-form label-position="left">
            <el-form-item v-for="(item, index) in scope.row.spec" :key="index" style="margin-bottom: 5px" :label="item.attr">
              <span>{{ item.val || '无' }}</span>
            </el-form-item>
            <el-form-item style="margin-bottom: 5px" label="备注">
              <span>{{ scope.row.remark || '无' }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column align="center" label="图录号" prop="number" width="70" />
      <el-table-column align="center" label="名称" prop="name" width="180" show-overflow-tooltip />
      <el-table-column align="center" label="库位" prop="location" width="70" show-overflow-tooltip />
      <el-table-column align="center" label="年代" prop="year" width="60" />
      <el-table-column align="center" label="起拍价" prop="start_price" :formatter="formatMoney" width="80" />
      <el-table-column align="center" label="预估价" prop="eval_price" width="120" />
      <el-table-column align="center" label="底价" prop="resr_price" :formatter="formatMoney" width="100" />
      <el-table-column align="center" label="状态" prop="state" width="120">
        <template slot-scope="scope">
          <el-tag :type="stateMap[scope.row.state].tag">{{ stateMap[scope.row.state].text }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="破损" prop="is_break" width="80">
        <template slot-scope="scope">
          <el-tag v-show="scope.row.is_break == 1" type="danger">破损</el-tag>
          <span v-show="scope.row.is_break == 0">-</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="送货人" prop="send_user" width="80" show-overflow-tooltip />
      <!-- <el-table-column align="center" label="购买人" prop="buy_user" width="80" show-overflow-tooltip />
      <el-table-column align="center" label="成交号牌" prop="buy_num" width="80" show-overflow-tooltip />
      <el-table-column align="center" label="成交价" prop="final_price" width="100">
        <template slot-scope="scope">
          <b style="color: #009788">{{ toThousands(scope.row.final_price) }}</b>
        </template>
      </el-table-column> -->
      <el-table-column align="center" label="ID号" prop="id_number" width="80" show-overflow-tooltip />
      <el-table-column align="center" label="入库日期" prop="indepot_date" width="80" show-overflow-tooltip />
      <el-table-column align="center" label="出库日期" prop="outdepot_date" width="80" show-overflow-tooltip />
      <el-table-column align="center" label="物流跟踪号" prop="track_number" width="100" show-overflow-tooltip />
      <el-table-column align="center" label="结算与否" prop="is_settlement" width="120">
        <template slot-scope="scope">
          <el-tag :type="settlementMap[scope.row.is_settlement].tag">{{ settlementMap[scope.row.is_settlement].text }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="作品介绍" prop="introduction" width="80" show-overflow-tooltip />
      <el-table-column align="center" label="检索关键词" prop="keyword" width="100" show-overflow-tooltip />
      <el-table-column align="center" label="销售链接" prop="link" width="80" show-overflow-tooltip />
      <el-table-column v-if="!(roles.includes('editor') && multiSelect)" fixed="right" align="center" label="操作" width="180">
        <template slot-scope="scope">
          <el-button-group>
            <el-button v-permission="['admin', 'editor']" size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button v-permission="['editor', 'outer']" size="mini" type="warning" @click="handleBreak(scope.row)">{{ scope.row.is_break == 1 ? '取消破损' : '破损' }}</el-button>
            <el-button v-permission="['auditor']" size="mini" type="primary" @click="handlePassNum(scope.row)">修改获拍</el-button>
            <el-button v-permission="['auditor']" size="mini" type="warning" @click="handleUpdateState(scope.row, 8)">过审</el-button>
            <el-button v-permission="['outer']" size="mini" type="primary" :disabled="scope.row.state !== 4 && scope.row.state !== 3" @click="handlePickUp(scope.row)">提货</el-button>
            <el-button v-if="scope.row.state === 3" v-permission="['cashier']" size="mini" type="primary" @click="createOrder('buy', scope.row)">创建订单</el-button>
            <el-button v-if="scope.row.state === 4 || scope.row.state === 5" v-permission="['cashier']" size="mini" type="primary" @click="createOrder('send', scope.row)">创建订单</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 修改获拍号 -->
    <el-dialog title="修改获拍" width="30%" center :visible.sync="dialogPassVisible">
      <el-form ref="passForm" :model="passTemp" :rules="passRules" label-position="left" label-width="80px">
        <el-form-item label="类型">
          <el-radio-group v-model="passTemp.is_company">
            <el-radio :label="false">个人</el-radio>
            <el-radio :label="true">代拍</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="号牌" :prop="!passTemp.is_company ? 'buy_num' : 'buy_user'">
          <el-input v-if="!passTemp.is_company" v-model.trim="passTemp.buy_num" />
          <el-select v-else v-model="passTemp.buy_user" :loading="bidcoLoading" placeholder="请选择代拍" @change="handleChange">
            <el-option v-for="item in bidcoList" :key="item.id" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="成交价">
          <el-input v-model="passTemp.final_price" :min="0" type="number" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogPassVisible = false">取消</el-button>
        <el-button :loading="passLoading" type="primary" @click="passWithNum">保存并过审</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { toThousands } from '@/utils'
import { setGoodsBreak, setGoodsState, passGoodsBuyNum } from '@/api/goods'
import { getAllBidCos } from '@/api/admin'

export default {
  name: 'GoodsTable',
  props: {
    listLoading: {
      type: Boolean,
      default: false
    },
    listData: {
      type: Array,
      default: () => []
    },
    multiSelect: {
      type: Boolean,
      default: false
    },
    emptyText: {
      type: String,
      default: '暂无数据'
    }
  },
  data () {
    return {
      stateMap: {
        '-1': { text: '无效', tag: 'info' },
        0: { text: '未开拍', tag: '' },
        1: { text: '正在拍卖', tag: 'danger' },
        3: { text: '待付款', tag: 'warning' },
        4: { text: '待提货', tag: 'success' },
        5: { text: '已提货', tag: 'success' },
        6: { text: '流拍', tag: 'info' },
        7: { text: '已结算', tag: 'success' },
        8: { text: '待审核', tag: 'danger' },
        9: { text: '已提货未付款', tag: 'warning' }
      },
      settlementMap: {
        0: { text: '否', tag: 'danger' },
        1: { text: '是', tag: 'success' }
      },
      dialogPassVisible: false,
      passTemp: {
        buy_num: '',
        buy_user: '',
        final_price: ''
      },
      passRules: {
        buy_num: [{ required: true, message: '号牌不能为空', trigger: 'blur' }],
        buy_user: [{ required: true, message: '请选择代拍', trigger: 'change' }]
      },
      passLoading: false,
      bidcoList: [],
      bidcoLoading: false
    }
  },
  computed: {
    roles () {
      return this.$store.getters.roles
    }
  },
  created () {
    this.fetchBidcos()
  },
  methods: {
    handleChange (e) {
      console.log(e)
    },
    fetchBidcos () {
      this.bidcoLoading = true
      getAllBidCos().then(res => {
        this.bidcoList = res.data
        this.bidcoLoading = false
      }).catch(err => {
        console.log(err)
        this.bidcoLoading = false
      })
    },

    handleEdit (row) {
      this.$router.push(`/goods/${row.id}`)
    },

    // 更新 破损状态
    handleBreak (row) {
      this.$prompt('更新备注', {
        confirmButtonText: '保存',
        inputType: 'textarea',
        inputValue: row.remark,
        closeOnClickModal: false,
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true
            const data = {
              id: row.id,
              is_break: Number(row.is_break) === 1 ? 0 : 1,
              remark: instance.inputValue
            }
            setGoodsBreak(data).then(res => {
              done()
              instance.confirmButtonLoading = false
              this.$message.success(res.msg)
              this.$emit('update')
            }).catch(err => {
              console.log(err)
              instance.confirmButtonLoading = false
            })
          } else {
            done()
          }
        }
      }).catch(() => {})
    },

    // 提货
    handlePickUp (row) {
      if (row.state == 4) {
        this.handleUpdateState(row, 5)
      } else if (row.state == 3) {
        this.handleUpdateState(row, 9)
      }
    },

    // 更新拍品状态
    handleUpdateState (row, targetState) {
      this.$confirm('确认进行此操作吗？', {
        type: 'warning'
      }).then(() => {
        const data = {
          id: row.id,
          state: targetState
        }
        setGoodsState(data).then(res => {
          this.$message.success(res.msg)
          this.$emit('update')
        }).catch(err => {
          console.log(err)
        })
      }).catch(() => {})
    },

    // 过审 修改号牌
    handlePassNum (row) {
      this.passTemp = {
        id: row.id,
        is_company: row.is_company,
        buy_num: row.buy_num,
        buy_user: row.buy_user,
        final_price: row.final_price
      }
      this.dialogPassVisible = true
      this.$nextTick(() => {
        this.$refs['passForm'].clearValidate()
      })
    },

    passWithNum () {
      this.$refs['passForm'].validate((valid) => {
        if (valid) {
          this.passLoading = true
          if (this.passTemp.is_company) {
            this.passTemp.buy_num = ''
          }
          passGoodsBuyNum(this.passTemp).then(res => {
            this.passLoading = false
            this.$emit('update')
            this.$message.success(res.msg)
            this.dialogPassVisible = false
          }).catch(err => {
            this.passLoading = false
            console.log(err)
          })
        }
      })
    },

    rowKey (row) {
      return row.id
    },
    formatMoney (row, column, cellValue) {
      return this.toThousands(cellValue)
    },
    handleSelectionChange (arr) {
      this.$emit('checkChange', arr)
    },
    createOrder (type, goodsRow) {
      const data = {
        type,
        goods: [goodsRow]
      }
      this.$emit('settle', data)
    },
    toThousands
  }
}
</script>

<style lang="scss" scoped>
.el-form {
  width: 80%;
  margin: auto;
  .el-select {
    width: 100%;
  }
}
</style>
